#include "stdafx.h"
#include "mysql_conn.h"
#include "MoneyTableData.h"
#include "mysqlconnpool.h"

CMysqlConn::CMysqlConn(char* url, char* user, char* password, char* dbname, unsigned int port)
{
	m_pstMysql = NULL;
	m_bIsConnected = false;

	m_strDbUrl = url;
	m_strDbUser = user;
	m_strDbPassword = password;
	m_strDbName = dbname;
	m_iDbPort = port;
}

CMysqlConn::~CMysqlConn()
{
	mysql_close(m_pstMysql);
	m_pstMysql = NULL;
	m_bIsConnected = false;
}

void CMysqlConn::InitConn()
{
	m_pstMysql = mysql_init(NULL);
	if (m_pstMysql == NULL)
	{
		return;
	}
	Connect();
}

bool CMysqlConn::Connect()
{
	//printf("url[%s],user[%s],password[%s]\n", m_strDbUrl.c_str(), m_strDbUser.c_str(), m_strDbPassword.c_str());
	if (mysql_real_connect(m_pstMysql, m_strDbUrl.c_str(), m_strDbUser.c_str(), m_strDbPassword.c_str(), m_strDbName.c_str(), m_iDbPort, NULL, 0) == NULL)
	{
		fprintf(stderr, "%s\n", mysql_error(m_pstMysql));
		return false;
	}
	m_bIsConnected = true;
	return true;
}
bool CMysqlConn::Reconnect()
{
	if (mysql_real_connect(m_pstMysql, m_strDbUrl.c_str(), m_strDbUser.c_str(), m_strDbPassword.c_str(), m_strDbName.c_str(), m_iDbPort, NULL, 0) == NULL){
		fprintf(stderr, "%s\n", mysql_error(m_pstMysql));
		return false;
	}
	m_bIsConnected = true;
	return true;
}

void CMysqlConn::CloseConnect()
{
	mysql_close(m_pstMysql);
	m_bIsConnected = false;
}

bool CMysqlConn::CheckConnection()
{
	return m_bIsConnected;
}

unsigned int CMysqlConn::QuerySQL(char* pStrSql, CTableData* pTableData)
{
	m_State = MYSQL_CONN_BUSY;
	int nRet = mysql_real_query(m_pstMysql, pStrSql, strlen(pStrSql));
	if (nRet != 0)
	{
		unsigned int uiLastError = mysql_errno(m_pstMysql);
		return uiLastError;
	}

	do
	{
		MYSQL_RES* pstMysqlRes = mysql_store_result(m_pstMysql);
		if (pstMysqlRes == NULL)
		{
			break;
		}

		int fieldnum = mysql_num_fields(pstMysqlRes);
		if (fieldnum != 0)
		{
			pTableData->AddTableData(pstMysqlRes);
		}

		mysql_free_result(pstMysqlRes);

	} while (!mysql_next_result(m_pstMysql));

	m_State = MYSQL_CONN_IDLE;

	CMysqlConnPool::Instance()->BacktoPool(this);
}

unsigned int CMysqlConn::ExcuteSQL(char* pStrSql)
{
	m_State = MYSQL_CONN_BUSY;
	int nRet = mysql_real_query(m_pstMysql, pStrSql, strlen(pStrSql));
	if (nRet != 0)
	{
		unsigned int uiLastError = mysql_errno(m_pstMysql);
		return uiLastError;
	}
	m_State = MYSQL_CONN_IDLE;

	CMysqlConnPool::Instance()->BacktoPool(this);
}

MYSQL_CONN_STATE CMysqlConn::GetConnectionState()
{
	return m_State;
}